<?php

namespace App\Console\Commands;

use App\Console\Base;
use App\Models\AgentProperty;
use App\Models\MailConfig;
use App\Models\MailRecord;
use App\Models\User;
use App\Models\Agent;
use common\utils\RSACrypt;
use App\Jobs\MailJob;
use common\enum\QueueEnum;

class SendEmail extends Base
{
    const SEND_TYPE_USER = 1;//会员层级
    const SEND_TYPE_AGENT = 2;//代理层级
    const SEND_TYPE_CUSTOM = 3;//自定义
    const STATUS_SENDED = 1;//已发布
    const STATUS_SENDING = 3;//发布中
    const BATCH = 10000;
    const USER_LEVEL = 1;  // 用户层级
    const AGENT = 2;       // 代理用户
    const CUSTOM = 3;      // 自定义
    const IS_EFFECT = 1;
    /**
     * 控制台命令 signature 的名称。
     *
     * @var string
     */
    protected $signature = self::PREFIX . 'sendemail {--hall_id=}';

    /**
     * 控制台命令说明。
     *
     * @var string
     */
    protected $description = 'SendEmail';

    /**
     * 执行控制台命令。
     *
     * @return mixed
     */
    public function handle()
    {

        $hallID = $this->option('hall_id');

        //查找等待发送的邮件
        $mailList = MailRecord::where(['status' => static::STATUS_SENDING, 'hall_id' => $hallID])->get();
        if ($mailList) {
            foreach ($mailList as $mail) {
                $content = $mail['content'];
                if ($mail['hyper_text'] == 1 && $mail['created_at'] > '2018-12-26 00:00:00') {
                    $content = base64_decode($mail['content']);
                }
                $title = $mail['title'];
                $send_type = $mail['send_type'];
                $this->info("send email: " . $title);
                $users = [];
                switch ($send_type) {
                    case self::USER_LEVEL:
                        $levels = explode(',', trim($mail['recipient']));
                        $users = User::where(['hall_id' => $hallID])->where('email', '<>', '')->whereIn('level_id', $levels)->distinct()->pluck('email');
                        break;
                    case self::AGENT:
                        $users = AgentProperty::where(['hall_id' => $hallID])->where('email', '<>', '')->distinct()->pluck('email');
                        break;
                    case self::CUSTOM:
                        $recipient = explode(',', trim($mail['recipient'], ','));
                        $users = User::where(['hall_id' => $hallID])->whereIn('username', $recipient)->pluck('email');
                        break;
                }
                foreach ($users as $u) {
                    $this->sendEmali($hallID, $u, $title, $content);
                }
                //修改邮件发送状态
                $mail->update(['status' => static::STATUS_SENDED]);
            }
        }
        $this->info("send email finished");

    }

    /**
     * 塞到邮件队列去
     * @param int $hallID 厅ID
     * @param string $user 接收者，一次只发一个人
     * @param string $title 标题
     * @param string $content 内容
     */
    public function sendEmali($hallID, $user, $title, $content)
    {
        $mail = RSACrypt::rsaDecrypt($user);
        $pattern = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/";
        if (!preg_match($pattern, $mail, $matches)) {
            $this->error("Error mail: " . $mail);
            return;
        }
        dispatch((new MailJob($hallID, $mail, $title, $content))->onQueue(QueueEnum::EMAIL));
    }

}
